import { Form, Modal, Input, notification } from 'antd';

import roleService from '@/api/services/security/roleService';

import { Role } from '#/entity';

export type RoleModalProps = {
  formValue: Role;
  title: string;
  show: boolean;
  onOk: VoidFunction;
  onCancel: VoidFunction;
};

export function RoleModal({ title, show, formValue, onOk, onCancel }: RoleModalProps) {
  const [form] = Form.useForm();
  const onFinish = (values: any) => {
    if (formValue.id) {
      roleService.updateRole(formValue.id, values).then((res) => {
        if (res > 0) {
          notification.success({
            message: '角色更新成功',
            duration: 3,
          });
          onOk();
        } else {
          notification.error({
            message: '更新失败，请检查输入是否正确',
            duration: 3,
          });
        }
      });
    } else {
      roleService.createRole(values).then((res) => {
        if (res > 0) {
          notification.success({
            message: '角色创建成功',
            duration: 3,
          });
          onOk();
        } else {
          notification.error({
            message: '创建失败，请检查输入是否正确',
            duration: 3,
          });
        }
      });
    }
  };
  return (
    <Modal
      title={title}
      open={show}
      onCancel={onCancel}
      okButtonProps={{ autoFocus: true, htmlType: 'submit' }}
      destroyOnHidden
      modalRender={(dom) => (
        <Form
          initialValues={formValue}
          form={form}
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 18 }}
          onFinish={onFinish}
          clearOnDestroy
          layout="horizontal"
        >
          {dom}
        </Form>
      )}
    >
      <Form.Item<Role> label="名称" name="name" rules={[{ required: true }]}>
        <Input />
      </Form.Item>
      <Form.Item<Role> label="编码" name="code" rules={[{ required: true }]}>
        <Input />
      </Form.Item>

      <Form.Item<Role> label="备注" name="remark">
        <Input.TextArea />
      </Form.Item>
    </Modal>
  );
}
